#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Redis连接测试工具
专门用于测试Redis服务器连接状态
"""

import subprocess
import socket
import time
import json
from datetime import datetime

class RedisConnectionTester:
    def __init__(self, redis_host="test-redis.oyumwu.clustercfg.apne1.cache.amazonaws.com", redis_port=6379):
        self.redis_host = redis_host
        self.redis_port = redis_port
        
    def test_ping(self):
        """测试ping连接"""
        print(f"测试ping连接到 {self.redis_host}...")
        try:
            result = subprocess.run(['ping', '-c', '3', self.redis_host], 
                                  capture_output=True, text=True, timeout=30)
            return result.returncode == 0, result.stdout, result.stderr
        except subprocess.TimeoutExpired:
            return False, "", "Ping超时"
        except Exception as e:
            return False, "", str(e)
    
    def test_telnet(self):
        """测试telnet连接"""
        print(f"测试telnet连接到 {self.redis_host}:{self.redis_port}...")
        try:
            result = subprocess.run(['nc', '-z', '-v', self.redis_host, str(self.redis_port)], 
                                  capture_output=True, text=True, timeout=10)
            return result.returncode == 0, result.stdout, result.stderr
        except subprocess.TimeoutExpired:
            return False, "", "Telnet超时"
        except Exception as e:
            return False, "", str(e)
    
    def test_socket_connection(self):
        """测试socket连接"""
        print(f"测试socket连接到 {self.redis_host}:{self.redis_port}...")
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(10)
            result = sock.connect_ex((self.redis_host, self.redis_port))
            sock.close()
            return result == 0, f"连接{'成功' if result == 0 else '失败'}", ""
        except Exception as e:
            return False, "", str(e)
    
    def test_dns_resolution(self):
        """测试DNS解析"""
        print(f"测试DNS解析 {self.redis_host}...")
        try:
            result = subprocess.run(['nslookup', self.redis_host], 
                                  capture_output=True, text=True, timeout=10)
            return result.returncode == 0, result.stdout, result.stderr
        except subprocess.TimeoutExpired:
            return False, "", "DNS查询超时"
        except Exception as e:
            return False, "", str(e)
    
    def get_network_info(self):
        """获取网络信息"""
        print("获取网络信息...")
        info = {}
        
        # 获取路由表
        try:
            result = subprocess.run(['netstat', '-rn'], capture_output=True, text=True)
            info['routing_table'] = result.stdout
        except:
            info['routing_table'] = "获取失败"
        
        # 获取DNS配置
        try:
            result = subprocess.run(['scutil', '--dns'], capture_output=True, text=True)
            info['dns_config'] = result.stdout
        except:
            info['dns_config'] = "获取失败"
        
        # 获取网络接口
        try:
            result = subprocess.run(['ifconfig'], capture_output=True, text=True)
            info['network_interfaces'] = result.stdout
        except:
            info['network_interfaces'] = "获取失败"
        
        return info
    
    def run_comprehensive_test(self):
        """运行综合测试"""
        print("=" * 60)
        print("Redis连接综合测试")
        print("=" * 60)
        print(f"目标Redis服务器: {self.redis_host}:{self.redis_port}")
        print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("=" * 60)
        
        results = {
            'timestamp': datetime.now().isoformat(),
            'redis_host': self.redis_host,
            'redis_port': self.redis_port,
            'tests': {}
        }
        
        # 测试DNS解析
        dns_success, dns_stdout, dns_stderr = self.test_dns_resolution()
        results['tests']['dns_resolution'] = {
            'success': dns_success,
            'output': dns_stdout,
            'error': dns_stderr
        }
        print(f"DNS解析: {'✅ 成功' if dns_success else '❌ 失败'}")
        
        # 测试ping
        ping_success, ping_stdout, ping_stderr = self.test_ping()
        results['tests']['ping'] = {
            'success': ping_success,
            'output': ping_stdout,
            'error': ping_stderr
        }
        print(f"Ping测试: {'✅ 成功' if ping_success else '❌ 失败'}")
        
        # 测试telnet
        telnet_success, telnet_stdout, telnet_stderr = self.test_telnet()
        results['tests']['telnet'] = {
            'success': telnet_success,
            'output': telnet_stdout,
            'error': telnet_stderr
        }
        print(f"Telnet测试: {'✅ 成功' if telnet_success else '❌ 失败'}")
        
        # 测试socket连接
        socket_success, socket_stdout, socket_stderr = self.test_socket_connection()
        results['tests']['socket_connection'] = {
            'success': socket_success,
            'output': socket_stdout,
            'error': socket_stderr
        }
        print(f"Socket连接: {'✅ 成功' if socket_success else '❌ 失败'}")
        
        # 获取网络信息
        network_info = self.get_network_info()
        results['network_info'] = network_info
        
        # 保存测试结果
        with open('redis_connection_test_result.json', 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=2, ensure_ascii=False)
        
        print("=" * 60)
        print("测试结果总结:")
        print(f"DNS解析: {'✅' if dns_success else '❌'}")
        print(f"Ping连接: {'✅' if ping_success else '❌'}")
        print(f"Telnet连接: {'✅' if telnet_success else '❌'}")
        print(f"Socket连接: {'✅' if socket_success else '❌'}")
        print("=" * 60)
        
        if all([dns_success, ping_success, telnet_success, socket_success]):
            print("🎉 所有测试通过！Redis连接正常！")
        else:
            print("⚠️  部分测试失败，Redis连接可能有问题")
        
        print(f"详细结果已保存到: redis_connection_test_result.json")
        
        return results

if __name__ == "__main__":
    tester = RedisConnectionTester()
    tester.run_comprehensive_test()
